package com.refusea.train.domain.tx.impl

import com.refusea.train.domain.entity.ClassGroup
import com.refusea.train.domain.ex.BizEx
import com.refusea.train.domain.tx.ClassGroupTx
import com.refusea.train.mapper.ClassGroupMapper
import com.refusea.train.mapper.ClassGroupStudentMapper
import com.refusea.train.mapper.OrderMapper
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 * @author Zhang Yan 2024/4/8
 **/
@Service
@Transactional
class ClassGroupTxImpl(
    private val classGroupMapper: ClassGroupMapper,
    private val classGroupStudentMapper: ClassGroupStudentMapper,
    private val orderMapper: OrderMapper,

    ) : ClassGroupTx {

    override fun insert(classGroup: ClassGroup): Int {

        // insert class group
        classGroupMapper.insert(classGroup)

        // insert class group students
        classGroupStudentMapper.inserts(classGroup)

        val result = orderMapper.markGrouped(classGroup)
        if (result != classGroup.studentIds!!.size) {
            throw BizEx.of("更新订单状态失败")
        }

        return classGroup.id
    }

    override fun delete(classGroup: ClassGroup) {
        val size = classGroup.studentIds!!.size

        // update order status to 'PENDING'
        val result = orderMapper.deactivate(classGroup)
        if (result != size) {
            throw BizEx.of("更新订单状态失败")
        }

        // delete class group students
        if (classGroupStudentMapper.deletes(classGroup.id, classGroup.schoolId) != size) {
            throw BizEx.of("删除班级学生失败")
        }

        // delete class group
        if (classGroupMapper.delete(classGroup.id, classGroup.schoolId) != 1) {
            throw BizEx.of("删除班级失败")
        }
    }
}
